package com.example.demo.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description: 拦截器
 * @Author Landiy
 * @Emali yylandiy@163.com
 * @Date 2021/2/410:43
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${login-config.admin-pwd")
    private String adminPwd;
    @Value("${login-config.user-pwd")
    private String userPwd;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 开启登陆配置
            .authorizeRequests()
                // 所有都可访问
                .antMatchers("/static/**").permitAll()
                .antMatchers("/student/**").permitAll()
                // 仅admin角色可访问
                .antMatchers("/admin").hasRole("admin")
                // 符合其中一种角色可访问
                .antMatchers("/user").hasAnyRole("admin","user")
                // 其余登陆可访问
                .anyRequest().authenticated()
                .and()
            .formLogin()
                // 登陆页面
                .loginPage("/login")
                // 登陆处理URL
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .and()
            .logout()
                // 退出登陆URL
                .logoutUrl("/logout")
                .permitAll()
                .and()
            // 关闭防止跨域攻击
            .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // 在内存中穿件角色
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("user")
                .password(new BCryptPasswordEncoder().encode(userPwd))
                .roles("user");
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("admin"))
                .roles("user","admin");
    }

    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
